/**
 * 
 */
package com.imooc.security.core.validate.code;

import com.imooc.security.core.validate.code.image.ImageCode;
import com.imooc.security.core.validate.code.sms.SmsValidateCodeProesccor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhailiang
 *
 */
@Slf4j
@RestController
public class ValidateCodeController {

	private static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
	private static final String SESSION_SMS_KEY = "SESSION_KEY_SMS_CODE";

	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
	@Autowired
	ValidateCodeGenerator imageCodeGenerator;
	@Autowired

	SmsValidateCodeProesccor smsValidateCodeProesccor;

	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@GetMapping("/code/image")
	public void createCode(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ImageCode imagecode = (ImageCode) imageCodeGenerator.generate(request);
		sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imagecode);
		ImageIO.write(imagecode.getImage(), "JPEG", response.getOutputStream());

	}

	@GetMapping("/code/{type}")
	public void createSmsCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type)
			throws Exception {
		smsValidateCodeProesccor.create(new ServletWebRequest(request, response),type);
	}

}
